package cn.tedu._05mvcboot03.controller;

import cn.tedu._05mvcboot03.common.response.JsonResult;
import cn.tedu._05mvcboot03.common.response.StatusCode;
import cn.tedu._05mvcboot03.mapper.UserMapper;
import cn.tedu._05mvcboot03.pojo.dto.UserArticleDTO;
import cn.tedu._05mvcboot03.pojo.dto.UserLonginDTO;
import cn.tedu._05mvcboot03.pojo.entity.Mvc_article;
import cn.tedu._05mvcboot03.pojo.vo.ArticleVO;
import cn.tedu._05mvcboot03.pojo.vo.UserVO;
import com.fasterxml.jackson.databind.util.BeanUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import javax.validation.constraints.Size;

@Validated
@Api(tags = "01.用户模块")
@Slf4j
@RestController
@RequestMapping("/v1/users/")
public class UserContrller {
    @Autowired
    private UserMapper userMapper;

    @ApiOperation("登录功能")
    @PostMapping("login")
    public JsonResult login(@RequestBody @Validated UserLonginDTO userLonginDTO, @ApiIgnore HttpSession session) {
        log.debug("userLoginDTO=" + userLonginDTO);
        UserVO userVO = userMapper.selectByUsername(userLonginDTO.getUsername());
        if (userVO.getPassword().equals(userLonginDTO.getPassword())) {
            session.setAttribute("user", userVO);
            return new JsonResult(StatusCode.OPERATION_SUCCESS);
        }
        return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
    }

    @ApiOperation("发表文章")
    @PostMapping("article")
    public JsonResult atricle(@RequestBody @Validated UserArticleDTO userArticleDTO, @ApiIgnore HttpSession session) {
        log.debug("userArticleDTO = {}", userArticleDTO);

        UserVO userVO = (UserVO) session.getAttribute("user");
        System.out.println("userVO = " + userVO);
        if (userVO == null) {
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        Mvc_article mvcArticle = new Mvc_article();
        BeanUtils.copyProperties(userArticleDTO, mvcArticle);
        mvcArticle.setUserId(userVO.getId());
        userMapper.insert(mvcArticle);
        return new JsonResult(StatusCode.OPERATION_SUCCESS);


    }

    @ApiOperation("查询指定文章")
    @PostMapping("selectByArticleId")
    public JsonResult selectByArticleId(@Range(min = 1, max = 100, message = "文章id必须在1-100之间") @RequestParam Long id) {

        ArticleVO articleVO = userMapper.selectByArticleId(id);
        log.debug("selectByArticleId=" + articleVO);
//        if (articleVO==null){
//            return new JsonResult(StatusCode.VALIDATED_ERROR);
//        }
        return JsonResult.ok(articleVO);
    }
}
